package vn.cuhanh.utils;

import java.util.ArrayList;

import vn.cuhanh.R;
import vn.cuhanh.bean.Account;
import vn.cuhanh.bean.CharInfo;
import vn.cuhanh.bean.Game;
import vn.cuhanh.bean.PlayType;
import vn.cuhanh.sys.DBAdapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;

public class CuhanhDao {
	
	public static ArrayList<Game> getGameDataDatabase(Cursor cursor) {
		ArrayList<Game> games = new ArrayList<Game>();
		cursor.moveToFirst();
		while (cursor.isAfterLast() == false) {
			int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
			String name = cursor
					.getString(cursor.getColumnIndexOrThrow("name"));
			String image = cursor.getString(cursor
					.getColumnIndexOrThrow("image"));
			String nav_image = cursor.getString(cursor
					.getColumnIndexOrThrow("nav_image"));
			Game obj = new Game(id, name, image, nav_image);
			
			String strFeature = cursor.getString(cursor.getColumnIndexOrThrow("features"));
			String[] strArrayFeatures = strFeature.split(",");
			int[] pages = new int[strArrayFeatures.length];
			for(int i = 0; i < strArrayFeatures.length; i++) {
				pages[i] = Integer.valueOf(strArrayFeatures[i]);
			}
			obj.setPages(pages);
			
			games.add(obj);
			cursor.moveToNext();
		}
		return games;
	}

	public static CharInfo getCharInfoFromDatabase(Cursor cursor) {
		cursor.moveToFirst();
		CharInfo charInfo = null;
		if(cursor.isAfterLast()) {
			return charInfo;
		}
		charInfo = new CharInfo(
				cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
				cursor.getString(cursor.getColumnIndexOrThrow("name")),
				cursor.getLong(cursor.getColumnIndexOrThrow("score")),
				cursor.getString(cursor.getColumnIndexOrThrow("sex")),
				cursor.getString(cursor.getColumnIndexOrThrow("mate_name")),
				cursor.getLong(cursor.getColumnIndexOrThrow("charm")),
				cursor.getLong(cursor.getColumnIndexOrThrow("flower")),
				cursor.getLong(cursor.getColumnIndexOrThrow("eggs")),
				cursor.getLong(cursor.getColumnIndexOrThrow("online_time")),
				cursor.getLong(cursor.getColumnIndexOrThrow("m3g_money")),
				cursor.getLong(cursor.getColumnIndexOrThrow("food")),
				cursor.getLong(cursor.getColumnIndexOrThrow("soldiers"))
				);
		return charInfo;
	}
	
	public static ArrayList<PlayType> getPlayTypesFromDatabase(Cursor cursor) {
		ArrayList<PlayType> playTypes = new ArrayList<PlayType>();
		cursor.moveToFirst();
		while (cursor.isAfterLast() == false) {
			int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
			int gameId = cursor.getInt(cursor.getColumnIndexOrThrow("gameId"));
			String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
			String displayName = cursor.getString(cursor.getColumnIndexOrThrow("display_name"));
			String image = cursor.getString(cursor.getColumnIndexOrThrow("image"));
			String descriptionFileName = cursor.getString(cursor.getColumnIndexOrThrow("descript_file_name"));
			PlayType obj = new PlayType(id, gameId, name, displayName, image, descriptionFileName);
			playTypes.add(obj);
			cursor.moveToNext();
		}
		return playTypes;
	}
	
	public static void addCharInfoToDatabase(Context ctx, CharInfo charInfo, String userName) {
		ContentValues values = new ContentValues();
		values.put("username", userName);
		values.put("userId", charInfo.getId());
		values.put("name", charInfo.getName());
		values.put("score", charInfo.getScore());
		values.put("sex", charInfo.getSex());
		values.put("mate_name", charInfo.getMate_name());
		values.put("charm", charInfo.getCharm());
		values.put("flower", charInfo.getFlower());
		values.put("eggs", charInfo.getEggs());
		values.put("online_time", charInfo.getOnline_time());
		values.put("m3g_money", charInfo.getM3g_money());
		values.put("food", charInfo.getFood());
		values.put("soldiers", charInfo.getSoldier());
		DBAdapter dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(R.string.charInfoTable));
		
		try {
			if (dbAdapter.isClosed())
				dbAdapter.open();
			if(dbAdapter.insert(values) == -1) {
				dbAdapter.update(values, "username = '" + userName + "'");
			}
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} catch (IllegalArgumentException e) {
			HelperFunc.readStackTrace(e);
		} finally {
		}
		try {
			dbAdapter.close();
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
		
	}

	public static ArrayList<Game> getListGame(Context ctx) {
		DBAdapter dbAdapter;
		Cursor cursor = null;
		dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(
				R.string.gameTable));
		try {
			if (dbAdapter.isClosed()) {
				dbAdapter.open();
			}
			cursor = dbAdapter.fetchAll();

			if (cursor.getCount() > 0) {
				return getGameDataDatabase(cursor);
			} else {
				dbAdapter.delete(null);
				return null;
			}
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				if (cursor != null) {
					cursor.close();
				}
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		return null;
	}

	public static CharInfo getCharInfo(Context ctx, String userName) {
		DBAdapter dbAdapter;
		Cursor cursor = null;
		dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(
				R.string.charInfoTable));
		try {
			if (dbAdapter.isClosed()) {
				dbAdapter.open();
			}
			cursor = dbAdapter.fetch("username = '" + userName + "'");

			if (cursor.getCount() > 0) {
				return getCharInfoFromDatabase(cursor);
			}
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				if (cursor != null) {
					cursor.close();
				}
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		return null;
	}
	
	public static ArrayList<PlayType> getPlayTypes(Context ctx, int gameId) {
		DBAdapter dbAdapter;
		Cursor cursor = null;
		dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(
				R.string.playTypeTable));
		try {
			if (dbAdapter.isClosed()) {
				dbAdapter.open();
			}
			cursor = dbAdapter.fetch("gameId = " + gameId);

			if (cursor.getCount() > 0) {
				return getPlayTypesFromDatabase(cursor);
			}
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				if (cursor != null) {
					cursor.close();
				}
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		return null;
	}
	
	public static Account getAccountFromDatabase(Cursor cursor) {
		cursor.moveToFirst();
		if(cursor.isAfterLast()) {
			return null;
		}
		Account result = null;
		try {
			result = new Account(
					cursor.getInt(cursor.getColumnIndexOrThrow("userId")),
					cursor.getString(cursor.getColumnIndexOrThrow("userName")),
					cursor.getInt(cursor.getColumnIndexOrThrow("avatarNumber")),
					cursor.getString(cursor.getColumnIndexOrThrow("charName")),
					cursor.getInt(cursor.getColumnIndexOrThrow("dndScore")),
					cursor.getInt(cursor.getColumnIndexOrThrow("rank")),
					cursor.getInt(cursor.getColumnIndexOrThrow("zingMeId")),
					cursor.getInt(cursor.getColumnIndexOrThrow("gender")),
					cursor.getString(cursor.getColumnIndexOrThrow("zingMeAvatar")),
					cursor.getString(cursor.getColumnIndexOrThrow("zingMeProfileUrl")),
					cursor.getString(cursor.getColumnIndexOrThrow("zingMeName")),
					cursor.getString(cursor.getColumnIndexOrThrow("phoneNo")));
		} catch (Exception ex) {
			HelperFunc.readStackTrace(ex);
			return null;
		}
		return result;
	}
	
	public static Account getAccount(Context ctx) {
		DBAdapter dbAdapter;
		Cursor cursor = null;
		dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(
				R.string.accountTable));
		try {
			if (dbAdapter.isClosed()) {
				dbAdapter.open();
			}
			cursor = dbAdapter.fetchAll();

			if (cursor.getCount() > 0) {
				return getAccountFromDatabase(cursor);
			}
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				if (cursor != null) {
					cursor.close();
				}
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		return null;
	}
	
	public static void updateDndScore(Context ctx, String userName, int dndScore) {
		updateSingleAccountField(ctx, userName, "dndScore", dndScore);
	}
	
	public static void updateAvatarNumber(Context ctx, String userName, int avatarNumber) {
		updateSingleAccountField(ctx, userName, "avatarNumber", avatarNumber);
	}
	
	public static void updateSingleAccountField(Context ctx, String userName, String fieldName, String value) {
		DBAdapter adapter = new DBAdapter(ctx, ctx.getResources().getString(R.string.accountTable));
		try {
			if(adapter.isClosed()) {
				adapter.open();
			}
			ContentValues values = new ContentValues();
			values.put(fieldName, value);
			adapter.update(values, "userName = '" + userName + "'");
		} catch (SQLException e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				adapter.close();
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			}
		}
	}
	
	public static void updateSingleAccountField(Context ctx, String userName, String fieldName, int value) {
		DBAdapter adapter = new DBAdapter(ctx, ctx.getResources().getString(R.string.accountTable));
		try {
			if(adapter.isClosed()) {
				adapter.open();
			}
			ContentValues values = new ContentValues();
			values.put(fieldName, value);
			adapter.update(values, "userName = '" + userName + "'");
		} catch (SQLException e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				adapter.close();
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			}
		}
	}

	public static void addAccountToDatabase(Context ctx, Account account) {
		ContentValues values = new ContentValues();
		values.put("userName", account.getUserName());
		values.put("userId", account.getId());
		values.put("avatarNumber", account.getAvatarNumber());
		values.put("charName", account.getCharName());
		values.put("dndScore", account.getDndScore());
		values.put("rank", account.getRank());
		values.put("zingMeId", account.getZingMeId());
		values.put("gender", account.getGender());
		values.put("zingMeAvatar", account.getZingMeAvatar());
		values.put("zingMeProfileUrl", account.getZingMeProfileUrl());
		values.put("zingMeName", account.getZingMeName());
		values.put("phoneNo", account.getPhoneNo());
		DBAdapter dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(R.string.accountTable));
		
		try {
			if (dbAdapter.isClosed())
				dbAdapter.open();
			dbAdapter.deleteAll();
			dbAdapter.insert(values);
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} catch (IllegalArgumentException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
	}

	public static void clearAll(Context ctx) {
		// TODO Auto-generated method stub
		DBAdapter dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(R.string.accountTable));
		try {
			if (dbAdapter.isClosed())
				dbAdapter.open();
			dbAdapter.deleteAll();
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} catch (IllegalArgumentException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
	}
}
